package net.wanho.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.CaptchaConstant;
import net.wanho.dto.LoginAuthDto;
import net.wanho.exception.LoginAuthException;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.po.UserInfo;
import net.wanho.service.LoginAuthService;
import net.wanho.util.CurrentUtils;
import net.wanho.util.JwtUtil;
import net.wanho.vo.CaptchaVo;
import net.wanho.vo.LoginInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Author: Lun
 * Date: 2025-07-22 19:36
 * Description: <描述>
 */
@Service
@RequiredArgsConstructor
public class LoginAuthServiceImpl implements LoginAuthService {
    private final StringRedisTemplate redisTemplate;
    private final UserInfoMapper userInfoMapper;

    @Override
    public CaptchaVo captchaImage() {
        // 创建一个算术验证码对象
        ArithmeticCaptcha captcha = new ArithmeticCaptcha();
        // 设置验证码长度为2位
        captcha.setLen(2);
        CaptchaVo captchaVo = new CaptchaVo();
        // 将验证码图片转换为Base64编码并设置到验证码信息对象中
        captchaVo.setImg(captcha.toBase64());
        // 生成一个唯一的UUID并设置到验证码信息对象中
        String uuid = UUID.randomUUID().toString();
        captchaVo.setUuid(uuid);
        // 将验证码的值和UUID存储到Redis中，并设置过期时间为2分钟
        redisTemplate.opsForValue().set(CaptchaConstant.CAPTCHA_PREFIX + uuid, captcha.text(), CaptchaConstant.CAPTCHA_EXPIRE, TimeUnit.MINUTES);
        return captchaVo;
    }

    @Override
    public String login(LoginAuthDto loginAuthDto) {
        String captcha = redisTemplate.opsForValue().get(CaptchaConstant.CAPTCHA_PREFIX + loginAuthDto.getUuid());
        if (captcha != null  && !StrUtil.equals(loginAuthDto.getCode(), captcha)) {
            throw new LoginAuthException("验证码错误");
        }

        LambdaQueryWrapper<UserInfo> existWrapper = new LambdaQueryWrapper<>();
        existWrapper.eq(UserInfo::getUserCode, loginAuthDto.getUserCode())
                    .eq(UserInfo::getUserPwd, SecureUtil.md5(loginAuthDto.getUserPwd()));
        UserInfo user = userInfoMapper.selectOne(existWrapper);

        if (ObjUtil.isEmpty(user)) {
            throw new LoginAuthException("用户名或密码错误");
        }
        if (StrUtil.equals("1", user.getIsDelete())){
            throw new LoginAuthException("用户被禁用");
        }

        HashMap<String, Object> payload = new HashMap<>();
        payload.put("userId", user.getUserId());
        payload.put("userCode", loginAuthDto.getUserCode());
        redisTemplate.delete(CaptchaConstant.CAPTCHA_PREFIX + loginAuthDto.getUuid());
        return "Bearer " +JwtUtil.generate(payload);
    }

    @Override
    public LoginInfoVo currUser() {
        Integer userId = CurrentUtils.getId();
        if (ObjUtil.isEmpty(userId)){
            throw new LoginAuthException("未获取到id,请先登录");
        }
        UserInfo user = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUserId, userId));
        LoginInfoVo loginInfoVo = new LoginInfoVo();
        BeanUtils.copyProperties(user, loginInfoVo);
        return loginInfoVo;
    }

    @Override
    public void logout() {
        CurrentUtils.remove();
    }
}
